package org.jeecg.modules.power.device.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.Synchronized;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.app.v1.device.entity.*;
import org.jeecg.modules.app.v1.util.Const;
import org.jeecg.modules.power.device.entity.YlDevice;
import org.jeecg.modules.power.device.entity.YlDeviceCategory;
import org.jeecg.modules.power.device.entity.YlDeviceRecords;
import org.jeecg.modules.power.device.entity.YlWarehouse;
import org.jeecg.modules.power.device.mapper.YlDeviceMapper;
import org.jeecg.modules.power.device.service.*;
import org.jeecg.modules.power.group.entity.GroupUser;
import org.jeecg.modules.power.group.entity.YlGroup;
import org.jeecg.modules.power.group.service.IYlGroupService;
import org.jeecg.modules.power.shop.entity.YlShop;
import org.jeecg.modules.power.shop.service.IYlShopService;
import org.jeecg.modules.system.entity.SysUser;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * ---设备所有的审核过程需要锁定设备当前状态禁止修改---
 *
 * @Description: 设备表（初稿）
 * @Author: jeecg-boot
 * @Date:   2024-07-16
 * @Version: V1.0
 */
@Service
@RequiredArgsConstructor
public class YlDeviceServiceImpl extends ServiceImpl<YlDeviceMapper, YlDevice> implements IYlDeviceService {

    private final IYlGroupService ylGroupService;
    private final IYlDeviceCategoryService deviceCategoryService;
    private final IYlWarehouseService warehouseService;
    private final IYlDeviceOperateRecordsService deviceOperateRecordsService;

    /**------------------------------------后台用--------------------------------------------------------*/
    @Override
    public IPage<YlDevice> listAll(Page<YlDevice> page, String deviceMac, String deviceCategory) {
        return baseMapper.listAll(page, deviceMac, deviceCategory);
    }

    /**
     * 根据设备mac查询设备信息，包含当前所在的位置
     * @param deviceMac
     * @return
     */
    public YlDevice getDeviceByMac(String deviceMac){
        return baseMapper.getDeviceInfo(deviceMac);
    }



    /**------------------------------------后台用--------------------------------------------------------*/


    /**------------------------------------接口用--------------------------------------------------------*/
    //region 接口用


    /**=========================================设备汇总==start======================================================================*/
    //region 资产一览设备汇总

    /**
     * 查询BD下的设备汇总  或者分组下的设备汇总
     * @param flag 1小组（groupId为所在小组ID）2组员（groupId为组员ID）
     * @param groupId
     */
    public List<ApiDeviceCategoryEntity>  getAllDeviceByCategory(String flag,String groupId){

        List<YlDevice> deviceList = getAllDevice( flag, groupId);
        List<ApiDeviceCategoryEntity>  list = deviceCategoryService.getDeviceCategory();
        Map<String,List<YlDevice>> listMap = deviceList.stream().collect(Collectors.groupingBy(YlDevice::getDeviceCategory));

        /**
         * 一级分类
         */
        for(ApiDeviceCategoryEntity entity:list){
            List<ApiAllDeviceEntity> entityList = new ArrayList<>();
            List<ApiDeviceCategoryEntity> ch = entity.getChildren();
            List<YlDevice> tempList = getAllDeviceByCategoryList(ch,listMap);
            ApiAllDeviceEntity normal = getDeviceStatistics(tempList);
            normal.setCategoryName("全部");
            normal.setCategoryId("");
            entityList.add(normal);
            /**
             * 二级分类
             */
            for(ApiDeviceCategoryEntity category:ch){
                List<YlDevice> categoryDeviceList = category.getDeviceList();
                if(!categoryDeviceList.isEmpty()) {
                    ApiAllDeviceEntity categoryDevice = getDeviceStatistics(categoryDeviceList);
                    categoryDevice.setCategoryName(category.getName());
                    categoryDevice.setCategoryId(category.getId());
                    entityList.add(categoryDevice);
                }
            }
            entity.setEntityList(entityList);
            entity.setChildren(null);
        }
        return list;
    }
    /**
     *  查询小组或者门店所有设备信息
     * @param flag 1小组（groupId为所在小组ID）2组员（groupId为组员ID）
     * @param groupId
     * @return
     */
    public List<YlDevice> getAllDevice(String flag,String groupId){
        List<YlDevice> list = new ArrayList<>();
        /**
         * 1、分组门店设备： 分组查门店->设备
         *    分组BD设备 :  分组查BD ->设备
         * 2、BD门店设备： bd查门店->设备
         *    BD设备：   直接BD设备
         */
        if(Objects.equals(flag,Const.leader_1)){
            List<YlDevice> list_bd = getGroupBdDeviceList(groupId);
            List<YlDevice> list_shop = getGroupShopDeviceList(groupId);
            list.addAll(list_bd);
            list.addAll(list_shop);
        } else if (Objects.equals(flag,Const.leader_2)) {
            List<YlDevice> list_bd = getBdDeviceList(groupId);
            List<YlDevice> list_shop = getBdShopDeviceList(groupId);
            list.addAll(list_bd);
            list.addAll(list_shop);
        }
        List<YlDevice> storageList = selectStorageDevice();
        list.addAll(storageList);
        return list;
    }

    /**
     * 小组下的BD
     * @param groupId
     */
    public List<YlDevice> getGroupBdDeviceList(String groupId){
        return baseMapper.selectGroupBdDevice(groupId);
    }

    /**
     * 小组下的门店
     * @param groupId
     */
    public List<YlDevice> getGroupShopDeviceList(String groupId){
        return baseMapper.selectGroupShopDevice(groupId);
    }
    /**
     * BD下的门店设备
     * @param bdId
     */
    public List<YlDevice> getBdShopDeviceList(String bdId){
        return baseMapper.selectBdShopDevice(bdId);
    }
    /**
     * BD下的设备
     * @param bdId
     */
    public List<YlDevice> getBdDeviceList(String bdId){
        return baseMapper.selectBdDevice(bdId);
    }
    /**
     * 资产一览统计-仓库设备
     * @param
     * @return
     */
    public List<YlDevice> selectStorageDevice(){
        return baseMapper.selectStorageDevice();
    }

    //endregion
    /**=========================================设备汇总==end======================================================================*/

    /**=========================================下级设备==start======================================================================*/
    //region  设备汇总下级数据

    /**
     * 资产一览下级数据
     *
     * 查询BD下的设备汇总  或者分组下的设备汇总
     * @param flag 1小组（groupId为所在小组ID）2组员（groupId为组员ID）
     * @param groupId
     */
    public List<ApiDeviceCategoryEntity>  getBelowDeviceByCategory(String flag,String groupId){

        List<YlDevice> deviceList = getBdDevice( flag, groupId);

        List<ApiDeviceCategoryEntity>  list = deviceCategoryService.getDeviceCategory();
        Map<String,List<YlDevice>> listMap = deviceList.stream().collect(Collectors.groupingBy(YlDevice::getDeviceCategory));

        /**
         * 一级分类
         */
        for(ApiDeviceCategoryEntity entity:list){
            List<ApiAllDeviceEntity> entityList = new ArrayList<>();
            List<ApiDeviceCategoryEntity> ch = entity.getChildren();
            List<YlDevice> tempList = getAllDeviceByCategoryList(ch,listMap);
            ApiAllDeviceEntity all = new ApiAllDeviceEntity();
            List<ApiAllDeviceEntity> elist = getBdDeviceStatistics(tempList);
            all.setCategoryName("全部");
            all.setCategoryId("1");
            all.setEntityList(elist);
            entityList.add(all);
            /**
             * 二级分类
             */
            for(ApiDeviceCategoryEntity category:ch){
                List<YlDevice> categoryDeviceList = category.getDeviceList();
                if(!categoryDeviceList.isEmpty()) {
                    ApiAllDeviceEntity categoryDevice = new ApiAllDeviceEntity();
                    List<ApiAllDeviceEntity> celist = getBdDeviceStatistics(categoryDeviceList);
                    categoryDevice.setCategoryName(category.getName());
                    categoryDevice.setCategoryId(category.getId());
                    categoryDevice.setEntityList(celist);
                    entityList.add(categoryDevice);
                }
            }
            entity.setEntityList(entityList);
            entity.setChildren(null);
        }
        return list;
    }
    /**
     *  查询小组或者门店所有设备信息
     * @param flag 1小组（groupId为所在小组ID）2组员（groupId为组员ID）
     * @param groupId
     * @return
     */
    public List<YlDevice> getBdDevice(String flag,String groupId){
        List<YlDevice> list = new ArrayList<>();
        /**
         * 1、分组门店设备： 分组查门店->设备
         *    分组BD设备 :  分组查BD ->设备
         * 2、BD门店设备： bd查门店->设备
         *    BD设备：   直接BD设备
         */
        if(Objects.equals(flag,Const.leader_1)){
            List<YlDevice> list_bd = getGroupBdDeviceList(groupId);
            List<YlDevice> list_shop = getGroupShopDeviceList(groupId);
            list.addAll(list_bd);
            list.addAll(list_shop);
        } else if (Objects.equals(flag,Const.leader_2)) {
            List<YlDevice> list_bd = getBdDeviceList(groupId);
            List<YlDevice> list_shop = getBdShopDeviceList(groupId);
            list.addAll(list_bd);
            list.addAll(list_shop);
        }
        return list;
    }
    /**
     * 正常设备数据统计
     * @param tempList
     * @return
     */
    public List<ApiAllDeviceEntity> getBdDeviceStatistics(List<YlDevice> tempList){
        /**
         * 先筛选出门店和bd下的设备
         */
        List<YlDevice> deviceList = tempList.stream().filter(e->
                Objects.equals(e.getDeviceStatus(),Const.deviceStatus_3)||
                        Objects.equals(e.getDeviceStatus(),Const.deviceStatus_2)
        ).collect(Collectors.toList());

        Map<String,List<YlDevice>> tempListMap = deviceList.stream().collect(Collectors.groupingBy(YlDevice::getBdId));

        List<ApiAllDeviceEntity> entityList = new ArrayList<>();

        for(String bdId:tempListMap.keySet()){
            /**
             * bd下的设备
             */
            List<YlDevice> bdList = tempListMap.get(bdId);
            /**
             * BD下设备汇总
             */
            ApiAllDeviceEntity entity = getDeviceStatistics(bdList);
            entity.setCategoryId(bdId);
            GroupUser groupUser = getGroupUser(bdId);
            entity.setCategoryName(groupUser.getUserName());
            entityList.add(entity);
        }
        return entityList;
    }

    /**
     *  查询小组或者门店所有设备信息
     * @param flag 1小组（groupId为所在小组ID）2组员（groupId为组员ID）
     * @param groupId
     * @return
     */
    public List<YlDevice> getLowerBdDevice(String flag,String groupId){
        List<YlDevice> list = new ArrayList<>();
        /**
         * 1、分组门店设备： 分组查门店->设备
         *    分组BD设备 :  分组查BD ->设备
         * 2、BD门店设备： bd查门店->设备
         *    BD设备：   直接BD设备
         */
        if(Objects.equals(flag,Const.leader_1)){
            List<YlDevice> list_bd = getLowerGroupBdDeviceList(groupId);
            List<YlDevice> list_shop = getLowerGroupShopDeviceList(groupId);
            list.addAll(list_bd);
            list.addAll(list_shop);
        } else if (Objects.equals(flag,Const.leader_2)) {
            List<YlDevice> list_bd = getLowerBdDeviceList(groupId);
            List<YlDevice> list_shop = getLowerBdShopDeviceList(groupId);
            list.addAll(list_bd);
            list.addAll(list_shop);
        }
        return list;
    }
    /**
     * 小组下的BD
     * @param groupId
     */
    public List<YlDevice> getLowerGroupBdDeviceList(String groupId){
        return baseMapper.selectLowerGroupBdDevice(groupId);
    }

    /**
     * 小组下的门店
     * @param groupId
     */
    public List<YlDevice> getLowerGroupShopDeviceList(String groupId){
        return baseMapper.selectLowerGroupShopDevice(groupId);
    }
    /**
     * BD下的门店设备
     * @param bdId
     */
    public List<YlDevice> getLowerBdShopDeviceList(String bdId){
        return baseMapper.selectLowerBdShopDevice(bdId);
    }
    /**
     * BD下的设备
     * @param bdId
     */
    public List<YlDevice> getLowerBdDeviceList(String bdId){
        return baseMapper.selectLowerBdDevice(bdId);
    }
    //endregion
    /**=========================================下级设备==end======================================================================*/

    /**=========================================故障设备==start======================================================================*/
    // region 故障设备相关代码

    /**
     * 资产一览_故障设备_下级数据
     *
     * 查询BD下的设备汇总  或者分组下的设备汇总
     * @param flag 1小组（groupId为所在小组ID）2组员（groupId为组员ID）
     * @param groupId
     */
    public List<ApiDeviceCategoryEntity>  getFaultDeviceByCategory(String flag,String groupId){

        List<YlDevice> deviceList = getAllFaultDevice( flag, groupId);

        List<ApiDeviceCategoryEntity>  list = deviceCategoryService.getDeviceCategory();
        Map<String,List<YlDevice>> listMap = deviceList.stream().collect(Collectors.groupingBy(YlDevice::getDeviceCategory));

        /**
         * 一级分类
         */
        for(ApiDeviceCategoryEntity entity:list){
            List<ApiAllDeviceEntity> entityList = new ArrayList<>();
            List<ApiDeviceCategoryEntity> ch = entity.getChildren();
            getAllDeviceByCategoryList(ch,listMap);
            /**
             * 二级分类
             */
            for(ApiDeviceCategoryEntity category:ch){
                List<YlDevice> categoryDeviceList = category.getDeviceList();
                if(!categoryDeviceList.isEmpty()) {
                    ApiAllDeviceEntity categoryDevice = new ApiAllDeviceEntity();
                    List<ApiAllDeviceEntity> celist = getBdFaultDeviceStatistics(categoryDeviceList);
                    categoryDevice.setCategoryName(category.getName());
                    categoryDevice.setCategoryId(category.getId());
                    categoryDevice.setEntityList(celist);
                    entityList.add(categoryDevice);
                }
            }
            entity.setEntityList(entityList);
            entity.setChildren(null);
        }
        return list;
    }



    /**
     * 故障设备数据统计
     * @param tempList
     * @return
     */
    public List<ApiAllDeviceEntity> getBdFaultDeviceStatistics(List<YlDevice> tempList){
        /**
         * 先筛选出门店和bd下的设备
         */
        List<YlDevice> deviceList = tempList.stream().filter(e->
                Objects.equals(e.getDeviceStatus(),Const.deviceStatus_3)||
                        Objects.equals(e.getDeviceStatus(),Const.deviceStatus_2)
        ).collect(Collectors.toList());

        Map<String,List<YlDevice>> tempListMap = deviceList.stream().collect(Collectors.groupingBy(YlDevice::getBdId));

        List<ApiAllDeviceEntity> entityList = new ArrayList<>();

        for(String bdId:tempListMap.keySet()){
            /**
             * bd下的设备
             */
            List<YlDevice> bdList = tempListMap.get(bdId);
            /**
             * BD下设备汇总
             */
            ApiAllDeviceEntity entity = getFaultDeviceStatistics(bdList);
            entity.setCategoryId(bdId);
            GroupUser groupUser = getGroupUser(bdId);
            entity.setCategoryName(groupUser.getUserName());
            entityList.add(entity);
        }
        return entityList;
    }

    /**
     *  查询小组或者门店所有故障设备信息
     * @param flag 1小组（groupId为所在小组ID）2组员（groupId为组员ID）
     * @param groupId
     * @return
     */
    public List<YlDevice> getAllFaultDevice(String flag,String groupId){
        List<YlDevice> list = new ArrayList<>();
        /**
         * 1、分组门店设备： 分组查门店->设备
         *    分组BD设备 :  分组查BD ->设备
         * 2、BD门店设备： bd查门店->设备
         *    BD设备：   直接BD设备
         */
        if(Objects.equals(flag,Const.leader_1)){
            List<YlDevice> list_bd = getGroupBdFaultDeviceList(groupId);
            List<YlDevice> list_shop = getGroupShopFaultDeviceList(groupId);
            list.addAll(list_bd);
            list.addAll(list_shop);
        } else if (Objects.equals(flag,Const.leader_2)) {
            List<YlDevice> list_bd = getBdFaultDeviceList(groupId);
            List<YlDevice> list_shop = getBdShopFaultDeviceList(groupId);
            list.addAll(list_bd);
            list.addAll(list_shop);
        }
        return list;
    }

    /**
     * 小组下的BD
     * @param groupId
     */
    public List<YlDevice> getGroupBdFaultDeviceList(String groupId){
        return baseMapper.selectGroupBdFaultDevice(groupId);
    }

    /**
     * 小组下的门店
     * @param groupId
     */
    public List<YlDevice> getGroupShopFaultDeviceList(String groupId){
        return baseMapper.selectGroupShopFaultDevice(groupId);
    }
    /**
     * BD下的门店设备
     * @param bdId
     */
    public List<YlDevice> getBdShopFaultDeviceList(String bdId){
        return baseMapper.selectBdShopFaultDevice(bdId);
    }
    /**
     * BD下的设备
     * @param bdId
     */
    public List<YlDevice> getBdFaultDeviceList(String bdId){
        return baseMapper.selectBdFaultDevice(bdId);
    }
    //endregion
    /**========================================故障设备==end=======================================================================*/

    public ApiAllDeviceEntity getDeviceStatistics(List<YlDevice> tempList){
        Map<Integer,List<YlDevice>> tempListMap = tempList.stream().collect(Collectors.groupingBy(YlDevice::getDeviceStatus));
        /**
         * 设备状态1仓库2BD3门店9其他
         */
        List<YlDevice> shopList = tempListMap.get(Const.deviceStatus_3)==null?new ArrayList<>():tempListMap.get(Const.deviceStatus_3);
        List<YlDevice> bdList = tempListMap.get(Const.deviceStatus_2)==null?new ArrayList<>():tempListMap.get(Const.deviceStatus_2);
        List<YlDevice> storageList = tempListMap.get(Const.deviceStatus_1)==null?new ArrayList<>():tempListMap.get(Const.deviceStatus_1);

        List<YlDevice> shopNormalList = shopList.stream().filter(e-> Objects.equals(e.getIsFault(),1)).collect(Collectors.toList());
        List<YlDevice> bdNormalList = bdList.stream().filter(e-> Objects.equals(e.getIsFault(),1)).collect(Collectors.toList());
        List<YlDevice> storageNormalList = storageList.stream().filter(e-> Objects.equals(e.getIsFault(),1)).collect(Collectors.toList());

        List<YlDevice> shopFaultList = shopList.stream().filter(e-> Objects.equals(e.getIsFault(),2)).collect(Collectors.toList());
        List<YlDevice> bdFaultList = bdList.stream().filter(e-> Objects.equals(e.getIsFault(),2)).collect(Collectors.toList());
        List<YlDevice> storageFaultList = storageList.stream().filter(e-> Objects.equals(e.getIsFault(),2)).collect(Collectors.toList());

        Integer shopNumber = shopNormalList.size();
        Integer bdNumber = bdNormalList.size();
        Integer storageNumber = storageNormalList.size();
        Integer total = shopNumber+bdNumber+storageNumber;

        Integer shopFaultNumber = shopFaultList.size();
        Integer bdFaultNumber = bdFaultList.size();
        Integer storageFaultNumber = storageFaultList.size();

        ApiAllDeviceEntity all = new ApiAllDeviceEntity(total,shopNumber,bdNumber,storageNumber,
                shopFaultNumber,bdFaultNumber,storageFaultNumber);
        return all;
    }


    public ApiAllDeviceEntity getFaultDeviceStatistics(List<YlDevice> tempList){
        Map<Integer,List<YlDevice>> tempListMap = tempList.stream().collect(Collectors.groupingBy(YlDevice::getDeviceStatus));
        /**
         * 设备状态1仓库2BD3门店9其他
         */
        List<YlDevice> shopList = tempListMap.get(Const.deviceStatus_3)==null?new ArrayList<>():tempListMap.get(Const.deviceStatus_3);
        List<YlDevice> bdList = tempListMap.get(Const.deviceStatus_2)==null?new ArrayList<>():tempListMap.get(Const.deviceStatus_2);
        List<YlDevice> storageList = tempListMap.get(Const.deviceStatus_1)==null?new ArrayList<>():tempListMap.get(Const.deviceStatus_1);

        List<YlDevice> shopFaultList = shopList.stream().filter(e-> Objects.equals(e.getIsFault(),2)).collect(Collectors.toList());
        List<YlDevice> bdFaultList = bdList.stream().filter(e-> Objects.equals(e.getIsFault(),2)).collect(Collectors.toList());
        List<YlDevice> storageFaultList = storageList.stream().filter(e-> Objects.equals(e.getIsFault(),2)).collect(Collectors.toList());

        Integer shopFaultNumber = shopFaultList.size();
        Integer bdFaultNumber = bdFaultList.size();
        Integer storageFaultNumber = storageFaultList.size();
        ApiAllDeviceEntity all = new ApiAllDeviceEntity(0,0,0,0,
                shopFaultNumber,bdFaultNumber,storageFaultNumber);
        return all;
    }


    /**
     * 取一级分类下所有的设备
     * @param ch
     * @param listMap
     * @return
     */
    public List<YlDevice> getAllDeviceByCategoryList(List<ApiDeviceCategoryEntity> ch,Map<String,List<YlDevice>> listMap){
        List<YlDevice> list = new ArrayList<>();
        for(ApiDeviceCategoryEntity entity:ch){
            List<YlDevice> tempList = listMap.get(entity.getId());
            if(tempList != null && !tempList.isEmpty()){
                entity.setDeviceList(tempList);
                list.addAll(tempList);
            }
        }
        return list;
    }


    /**
     * 门店设备列表
     * @param shopId
     * @return
     */
    @Override
    public List<ApiShopDeviceEntity> queryShopDevice(String shopId) {
        return baseMapper.queryShopDevice(shopId);
    }
    /**
     * 门店设备列表
     * @param deviceId
     * @return
     */
    @Override
    public ApiShopDeviceDetailEntity queryShopDeviceDetail(String deviceId) {
        return baseMapper.queryShopDeviceDetail(deviceId);
    }


    public GroupUser getGroupUser(String userId){
        return ylGroupService.getUserGroup(userId);
    }

    /**
     * 跟设备编号获取设备信息
     * @param deviceNo
     * @return
     */
    public YlDevice getDeviceByNo(String deviceNo){
        QueryWrapper<YlDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(e->e.eq("device_sn",deviceNo).or().eq("device_mac",deviceNo)).last("limit 1");
        return this.getOne( queryWrapper);
    }

    /**
     * 锁定设备
     * @param id
     * @param lockId 锁定设备的业务ID
     * @return
     */
    @Synchronized
    public boolean lock(String id,String lockId){
        UpdateWrapper wrapper = new UpdateWrapper<>();
        wrapper.set("device_lock",lockId);
        wrapper.eq("id",id);
        wrapper.eq("device_lock",1);
        return this.update(wrapper);
    }

    /**
     * 当前设备是否解锁
     * @param id 设备ID
     * @return
     */
    public boolean islock(String id){
        QueryWrapper<YlDevice> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        wrapper.eq("device_lock",1);
        Optional<YlDevice> deviceOptional = Optional.ofNullable(this.getOne(wrapper));
        return deviceOptional.isPresent();
    }


    /**
     * 解锁设备
     * @param id
     * @param lockId 解锁设备的业务ID
     * @return
     */
    @Synchronized
    public boolean unlock(String id,String lockId){
        UpdateWrapper wrapper = new UpdateWrapper<>();
        wrapper.set("device_lock",1);
        wrapper.eq("id",id);
        wrapper.eq("device_lock",lockId);
        return this.update(wrapper);
    }

    /**
     * 资产/门店设备
     * @param page
     * @param categoryId
     * @return
     */
    @Override
    public List<ApiDeviceEntity> shopDeviceList(Page<ApiDeviceEntity> page, String categoryId,String flag,String groupId) {
        IPage<ApiDeviceEntity> deviceIPage = baseMapper.shopDeviceList(page, flag,groupId,categoryId);
        return deviceIPage.getRecords();
    }

    /**
     * 资产/BD设备
     * @param page
     * @param categoryId
     * @return
     */
    @Override
    public List<ApiDeviceEntity> bdDeviceList(Page<ApiDeviceEntity> page, String categoryId,String flag,String groupId) {
        IPage<ApiDeviceEntity> deviceIPage = baseMapper.bdDeviceList(page, flag,groupId,categoryId);
        return deviceIPage.getRecords();
    }

    /**
     * 资产/仓库设备
     * @param page
     * @return
     */
    @Override
    public List<ApiDeviceEntity> storeDeviceList(Page<ApiDeviceEntity> page,String categoryId) {
        IPage<ApiDeviceEntity> deviceIPage = baseMapper.storeDeviceList(page,categoryId);
        return deviceIPage.getRecords();
    }




    /**
     * 判断当前设备是否在BD下或者BD的门店下
     * 设备报修用吧。。。。。
     * 只能对位置在本人的设备进行退库申请
     * 有在桩宝，请通电上线后将宝弹出，无法上线或依旧存在
     * 在桩宝，请走故障退库
     * @param device
     * @param bdId
     * @return
     */
    public boolean isReturn(YlDevice device,String bdId){
        /**
         * 如果设备在BD下，判断businessId与当前bdId是否相同
         */
        if(Objects.equals(device.getDeviceStatus(),Const.deviceStatus_2) && Objects.equals(device.getBusinessId(),bdId))return true;
        return false;
    }

    /**
     * 设备绑定门店
     * @param deviceId
     * @param shopId
     */
    public void bindShop(String deviceId,String shopId){
        UpdateWrapper wrapper = new UpdateWrapper<>();
        wrapper.set("business_id",shopId);
        wrapper.set("device_status",Const.deviceStatus_3);
        wrapper.eq("id",deviceId);
        this.update(wrapper);
        bind(deviceId,shopId,Const.deviceStatus_3);
    }
    /**
     * 设备转移后绑定新的BD
     * @param deviceId
     * @param userId
     */
    public void bindUser(String deviceId,String userId){
        bind(deviceId,userId,Const.deviceStatus_2);
    }
    /**
     * 设备转移后绑定新的BD
     * @param deviceId
     * @param businessId 对应的业务ID
     * @param type 设备状态1仓库2BD3门店9其他
     */
    public void bind(String deviceId,String businessId,Integer type){
        UpdateWrapper wrapper = new UpdateWrapper<>();
        wrapper.set("business_id",businessId);
        wrapper.set("device_status",type);
        wrapper.eq("id",deviceId);
        this.update(wrapper);
    }

    /**
     * 运维操作
     * @param deviceId
     * @param deviceMac
     * @param type
     * @param hatch
     * @param bd
     */
    public void operate(String deviceId, String deviceMac, Integer type, String hatch,String reason, SysUser bd){

        GroupUser user = this.getGroupUser(bd.getId());
        /**
         * 后续增加设备相关信息的查询校验
         * 增加运维操作记录
         */
        deviceOperateRecordsService.operate(deviceId, deviceMac, type, hatch,reason, user);
    }


    //endregion
    /**------------------------------------接口用--------------------------------------------------------*/


    @Override
    public Map<String, Object> getShopIdDeviceQuantity(String shopId) {
        return baseMapper.getShopIdDeviceQuantity(shopId);
    }
}
